import sys
import os
import requests
import yaml
import logging
from datetime import datetime
# 改为从 utils.report_generator 导入 calculate_statistics
from utils.report_generator import calculate_statistics

logger = logging.getLogger("AppAutomation")


def send_feishu_message(
        success_rate: float,
        total_cases: int,
        passed_cases: int,
        failed_cases: int,
        error_cases: int,
        skipped_cases: int,
        duration: str
):
    try:
        # 获取项目根目录的绝对路径
        project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        config_path = os.path.join(project_root, "data", "config.yaml")
        
        # 明确指定使用 utf-8 编码读取配置文件
        with open(config_path, "r", encoding="utf-8") as f:
            config = yaml.safe_load(f)

        feishu_config = config.get("feishu")
        if not feishu_config or "webhook_url" not in feishu_config or not feishu_config["webhook_url"]:
            logger.warning("飞书配置缺失或不完整，跳过发送通知。")
            return

        webhook_url = feishu_config["webhook_url"]

        # 构造飞书消息内容
        message_content = f"""【Joyhub-UI-自动化通知】
运行环境：测试环境
测试负责人：杨鹏程
执行结果
成功率: {success_rate:.2f}%
用例总数：{total_cases}
成功用例数：{passed_cases}
失败用例数：{error_cases}
异常用例数：{failed_cases}
跳过用例数：{skipped_cases}
用例执行时长：{duration}
时间：{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
非相关负责人员可忽略此消息。"""

        payload = {
            "msg_type": "text",
            "content": {
                "text": message_content
            }
        }

        response = requests.post(webhook_url, json=payload)
        if response.status_code == 200:
            logger.info("飞书通知发送成功。")
        else:
            logger.error(f"飞书通知发送失败，状态码: {response.status_code}, 响应: {response.text}")
    except Exception as e:
        logger.error(f"发送飞书通知时出现异常: {e}")